/*
=================================================================
= Title: NatLib  
= Desc: Collection of javascript functions to display google charts with Nabton data 
= Author: Adam Saxén
= Copywrite Nabton.com 2014-2015
= Revision history: 
= 2015-05-01 - Added more functionality 
= 2015-01-12 - Complete rebuild of library
= 2014-07-14 - Added comments to library  
=================================================================
*/

//=============== Initial variables (Global)
var currentData; //Current Graph data

//Current Sid-data-array
var appDataArray;
var currentAppData;

//Sid selection - App Manager page
var currentSidSelection = [];

//#############################################
//# Main program
//# Description: Called when page is loaded and ready
//#############################################
$(document).ready(function () {
	console.log("-Page Ready!");
    
    //Load page manager
    $('.pageLink').click(function (e) {
        e.preventDefault();
        var answerid = $(this).attr('id');
        pageManager(answerid);   
    });
    
    //Load default page
    pageManager(0); 
});


//#############################################
//# Page manager function
//# Description: Loads different php pages
//#############################################
function pageManager(pageId){
    console.log('pageManager called');

    $.ajax({
            url:		'pageLoader.php',
            dataType:	'text',
            success:	loadPageContent,
            error:      loadErrorPage,
            type:		'POST',
            data:		{ 
                            pageId: pageId
                        }
	    });
    
    function loadPageContent(data)
    {
        //Populate homepage body
        $('#contentWrap').html(data);

        $('#loginForm').submit(function(e){
            e.preventDefault();
            console.log("-Login started");
            loginManager(1);     
        });

        $('#logOut').click(function(e){
            e.preventDefault();
            console.log("-Logout started");
            loginManager(0);
        }); 

        //Load more content & scripts depending on page selection
        switch(pageId) 
        {
            case '0' :
      
                break;
            case '2' :
                $.getScript("libraries/nabHandlers.js").done(function( script, textStatus ) {
                    console.log( "nabHandlers.js loaded" );

                    $.getScript("libraries/nabCharts.js").done(function( script, textStatus ) {
                        console.log( "nabCharts.js loaded" );

                         $.ajax({
                            url:		'nabtonData.php',
                            dataType:	'json',
                            success:	populateApplicationsFormHandler,
                            error:		errorHandler("Failed to populate application list"),
                            type:		'POST',
                            data:		{ 
                                            action: 'fetchApplications'
                                        }
                        });  
                    });
                }); 
                break;
            case '3' :
                //Manage app links
                currentSidSelection = [];
                
                $('.manageAppLink').click(function (e) {
                    e.preventDefault();
                    var action = $(this).attr('id');
                    var appid = $(this).attr('appid');
                    appManager(action, appid);  
                });    
                
                $('#app_sid_select').change(function (e) {
                    //e.preventDefault();
                    appManager("addSidToApp", $(this).val());
                });
                break;
        }      
    }
    
    function loadErrorPage()
    {
        $('#contentWrap').html("Error loading page");
    }

}


//#############################################
//# App manager function
//# Description: manages Apps and sids
//#############################################
function appManager(action, id){
    console.log('App manager called:'+action);
    
    var title_app     = '';   
    var access_app    = '';
    var chart_type_app = '';
    
    
    if(action == "createApp")
    {
        
        console.log("data");
        var title_app      = $("#app_title").val();    
        var access_app     = $("#app_access option:selected").val();
        var chart_type_app = $("#app_chartType option:selected").val();
        
        console.log("Creating app:" + title_app);
        $.ajax({
            url:		'nabtonEdit.php',
            dataType:	'text',
            success:	manageDataSuccess,
            error:      manageDataError,
            type:		'POST',
            data:		{
                            action: action,
                            titleApp: title_app,
                            idApp: id,
                            accessApp: access_app,
                            chartTypeApp: chart_type_app,
                            selectedSids: currentSidSelection
                        }
        });
        currentSidSelection = [];
        
    }
    else if(action == "deleteApp")
    {
       
        console.log("appid:" + id);
        currentSidSelection = [];
        $.ajax({
            url:		'nabtonEdit.php',
            dataType:	'text',
            success:	manageDataSuccess,
            error:      manageDataError,
            type:		'POST',
            data:		{
                            action: action,
                            titleApp: title_app,
                            idApp: id,
                            accessApp: access_app,
                            chartTypeApp: chart_type_app,
                            selectedSids: currentSidSelection
                        }
        });
        
        
    }
    else if (action == "addSidToApp")
    {
        var sid = id;
        if ($.inArray(sid, currentSidSelection) < 0)
        {
            currentSidSelection.push(sid);
            $( "#selectedIds" ).append( "<div> "+ $('#app_sid_select option:selected').text() +" </div>" );
        }
        else
        {
            console.log("sid already selected");
        } 
    }
    

    
    function manageDataSuccess(data)
    {
        console.log(data);
        console.log("ManageData - Success!");
        //Refresh managePage
        pageManager(3);
        
    }
    
    function manageDataError(data1)
    {
        console.log(data);
        console.log("ManageData - Failed!");
    }

}

//#############################################
//# Login manager function
//# Description: Handles login
//#############################################
function loginManager(action)
{
    var $inputs = $('#loginForm :input');  
    //Get values from login form
    var values = {};
    $inputs.each(function() {
        values[this.name] = $(this).val();
    });

    if(action == 1)
    {
        $.ajax({
            url:		'nabtonLogin.php', 
            dataType:	'json', 
            success:	loginHandler,
            error:		loginErrorHandler("Failed to login"),
            type:		'POST', 

            data:		{ 
                            action: 'login',
                            usr:	values['usr'],
                            pswd:   values['pswd']
                        }
        });
    }
    else if(action == 0)
    {
        $.ajax({
            url:		'utils/resetAll.php', 
            dataType:	'json', 
            success:	logoutHandler,
            error:		loginErrorHandler("Failed to logout"),
            type:		'POST'
        });
    }
    
    
    function loginHandler(data){
        console.log('loginHandler - called');
        console.log(data); 

        if (data == 1)
        {
            var url = window.location.href;
            var index = url.indexOf("?p=");
            var urlShort=url.substr(0,index);
            window.location.replace(urlShort);
        }	
    }

    function logoutHandler(data){
        console.log('logoutHandler - called');
        console.log(data); 

        if (data == 1)
        {
            //Reload page
            location.reload(true);
        }	
    }
    
    function loginErrorHandler(textStatus)
    {
        console.log(textStatus);
    }
}



